import type { AppRouteRecordRaw, AppRouteModule } from '/@/router/types';

import { PAGE_NOT_FOUND_ROUTE, REDIRECT_ROUTE } from '/@/router/routes/basic';
import { treeMap } from '/@/utils/helper/treeHelper';
import { cloneDeep } from 'lodash-es';
import { mainOutRoutes } from './mainOut';

import { t } from '/@/hooks/web/useI18n';

// import.meta.globEager() 直接引入所有的模块 Vite 独有的功能
const modules: Record<string, any> = import.meta.glob('./modules/**/*.ts', { eager: true });

export const parentRouteModuleList: AppRouteModule[] = [];
const routeModuleList: AppRouteModule[] = [];

// 加入到路由集合中
Object.keys(modules).forEach((key) => {
  const mod = modules[key].default || {};
  const modList = Array.isArray(mod) ? [...mod] : [mod];

  routeModuleList.push(...modList);
  parentRouteModuleList.push(...modList);
});

export const asyncRoutes = [PAGE_NOT_FOUND_ROUTE, ...routeModuleList];

export const LoginRoute: AppRouteRecordRaw = {
  path: '/login',
  name: 'Login',
  component: () => import('/@/views/sys/login/Login.vue'),
  meta: {
    title: t('routes.basic.login'),
  },
};

export const ParentRootRoute: AppRouteRecordRaw = {
  path: '/',
  name: 'Root',
  redirect: '/home',
  meta: {
    title: 'Root',
  },
};

// Basic routing without permission
// 未经许可的基本路由
export const parentBasicRoutes = [
  ParentRootRoute,
  REDIRECT_ROUTE,
  PAGE_NOT_FOUND_ROUTE,
  ...mainOutRoutes,
];
// LoginRoute,
// RootRoute,
// ...mainOutRoutes,
// REDIRECT_ROUTE,
// PAGE_NOT_FOUND_ROUTE,
export const basicRoutes = [...parentBasicRoutes, LoginRoute, ...mainOutRoutes];

export function treeList(routeModList: any) {
  const list = treeMap(routeModList, {
    conversion: (node: any) => {
      const {
        name,
        path,
        meta: { title },
      } = node;
      return {
        key: name,
        name: title,
        path,
      };
    },
  });
  return cloneDeep(list);
}
